﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Text.RegularExpressions;

namespace WpfAdvControls.Process
{
    /// <summary>
    ///     Класс для запуска внешнего процесca
    ///     С гибкой возможностью задачи атрибутов через список ключей
    /// </summary>
    public class CommandInvoker : INotifyPropertyChanged
    {
        /// <summary>
        ///     Dictionary of arguments of the invoking command
        ///     Add pairs with key that used in pattern and value
        /// </summary>
        public Dictionary<string, string> Args = new Dictionary<string, string>();

        /// <summary>
        ///     arguments pattern
        /// </summary>
        private string argumentsPattern;

        /// <summary>
        ///     path to exe
        /// </summary>
        private string command;

        /// <summary>
        ///     Command - Path to exe
        /// </summary>
        public string Command
        {
            get { return command; }
            set
            {
                command = value;
                NotifyPropertyChanged("Command");
            }
        }

        /// <summary>
        ///     Arguments pattern. Example: "%1 %2 %3 %4"
        ///     Then %1, %2, %3, %4 keys of the pattern.
        /// </summary>
        public string ArgumentsPattern
        {
            get { return argumentsPattern; }
            set
            {
                argumentsPattern = value;
                NotifyPropertyChanged("ArgumentsPattern");
            }
        }


        public bool IsValid()
        {
            if (System.IO.File.Exists(Command))
            {
                return true;
            }
            return false;
        }

        public void Validation()
        {
            if (!IsValid())
            {
                throw new CommandInvokerException(string.Format("Command '{0}' is not valid", Command));
            }
        }

        /// <summary>
        ///     Run command with arguments from Args dictionary in order of ArgumentsPattern
        /// </summary>
        public void Invoke()
        {
            try
            {
                var arguments = ArgumentsPattern;
                // make key pattern : (key1)|(key2)|(key3)...(keyN)
                var keys = (from key in Args.Keys select "(" + key + ")").ToArray();
                var keyPattern = string.Join("|", keys);
                arguments = Regex.Replace(arguments, keyPattern, (Match match) =>
                {
                    string val;
                    if (!Args.TryGetValue(match.Value, out val))
                    {
                        val = "";
                    }
                    return val;
                });
                var process = new System.Diagnostics.Process();
                process.EnableRaisingEvents = true;
                process.Exited += ProcessExited;
                process.StartInfo = new ProcessStartInfo {FileName = Command, Arguments = arguments};
                process.Start();
            }
            catch (Exception ex)
            {
                var sb = new StringBuilder();
                sb.Append("Error running CommandInvoker");
                sb.AppendFormat(" Command: {0}", Command);
                sb.AppendFormat(" ArgumentsPattern: {0}", ArgumentsPattern);
                sb.AppendLine();
                foreach (var arg in Args)
                {
                    sb.AppendFormat("  Args[{0}]={1}", arg.Key, arg.Value);
                    sb.AppendLine();
                }
                throw new CommandInvokerException(sb.ToString(), ex);
            }
        }

        private void ProcessExited(object sender, EventArgs e)
        {
            if (ProcessEnded != null)
            {
                ProcessEnded(this, new EventArgs());
            }
        }

        public event EventHandler<EventArgs> ProcessEnded;

        [Serializable]
        public class CommandInvokerException : Exception
        {
            public CommandInvokerException()
            {
            }

            public CommandInvokerException(string message) : base(message)
            {
            }

            public CommandInvokerException(string message, Exception inner) : base(message, inner)
            {
            }

            protected CommandInvokerException(
                SerializationInfo info,
                StreamingContext context) : base(info, context)
            {
            }
        }

        #region INotifyPropertyChanged Members

        public event PropertyChangedEventHandler PropertyChanged;

        private void NotifyPropertyChanged(string property)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(property));
            }
        }

        #endregion
    }
}